﻿using System;
using System.Security.Authentication;
using EduFormManager.Models;
using EduFormManager.Models.Repo;

namespace EduFormManager
{
    class Authentication
    {
        public static Credentials CurrentCredentials { get; set; }

        public class AuthenticatedArgs : EventArgs
        {
            public AuthenticatedArgs() { }
            public AuthenticatedArgs(Credentials cred)
            {
                this.Credentials = cred;
            }
            public Credentials Credentials { get; set; }
        }

        public event EventHandler<AuthenticatedArgs> Authenticated;

        public Credentials GetAuthenticated(String login, String password)
        {
            ApplicationRepository repo = (ApplicationRepository)RepositoryFactory.Instance.Repository;
            try
            {
                Credentials cred = repo.GetCredentials(login, password);

                if (cred == null)
                {
                    throw new InvalidCredentialException("Неверный логин или пароль");
                }

                AuthenticatedArgs args = new AuthenticatedArgs {Credentials = cred};
                CurrentCredentials = cred;
                OnAuthenticated(args);

                return cred;
            }
            catch (Exception)
            {
                throw;
            }
        }

        protected virtual void OnAuthenticated(AuthenticatedArgs e)
        {
            EventHandler<AuthenticatedArgs> handler = Authenticated;
            if (handler != null)
            {
                handler(this, e);
            }
        }
    }
}
